package com.xc.dbinit;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbinitApplication {
    @Autowired
    private DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(DbinitApplication.class, args);
    }

    // 初始化方法中,执行四个sql脚本文件
    @PostConstruct
    public void init() throws SQLException {
//        exec("sql/init.txt");
//        exec("sql/admininit.txt");
//        exec("sql/dr.txt");
        exec("sql/31.sql");
    }

    private void exec(String sql) throws SQLException {
        ClassPathResource cpr = new ClassPathResource(sql, DbinitApplication.class.getClassLoader());
        EncodedResource resource = new EncodedResource(cpr);
        // spring提供的执行 sql 脚本的工具
        ScriptUtils.executeSqlScript(dataSource.getConnection(), resource);
    }
}
